import { userService } from './../../api/request/user-service';
import { UserInfoModel } from './user-info-model';
import { BehaviorSubject } from 'rxjs';

const USER_INFO_CACHE_KEY = 'user_info_cache_key';
const USER_TOKEN_CACHE_KEY = 'user_token_cache_key';
export class AuthService {
    /**
     * 用户的信息
     */
    private _obUserInfo = new BehaviorSubject<UserInfoModel | null>( null);
    private _obToken = new BehaviorSubject('');

    constructor(settings: ObjectMap) {
        this.init();
    }

    /**
     * 初始化token
     */
    public async init() {
        const token = wx.getStorageSync(USER_TOKEN_CACHE_KEY);
        if (token) {
            this._obToken.next(token);
        }
    }
    public get token() {return this._obToken.getValue();}

    /**
     * 设置用户信息
     * @param data 用户信息
     */
    public async setUserInfo(data: UserInfoModel) {
        wx.setStorageSync(USER_INFO_CACHE_KEY, data);
        this._obUserInfo.next(data);
    }
    /**
     * 登陆
     * @param code 临时code
     */
    public async login(code: string) {
        const token = await userService.login(code);
        this.setToken(token);
    }
    /**
     * 登出
     * @param code 临时code
     */
    public async loginOut() {
        wx.removeStorageSync(USER_INFO_CACHE_KEY);
        wx.removeStorageSync(USER_TOKEN_CACHE_KEY)
    }

    /**
     * 设置token
     * @param token 
     */
    public setToken(token: string) {
        wx.setStorageSync(USER_TOKEN_CACHE_KEY, token);
        this._obToken.next(token);
    }
}